package com.yfbao.horizon.schedule.tk.common;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.io.IOException;

@Slf4j
public class JacksonRedisSerializer implements RedisSerializer {

    private int bigDataSize;
    private ObjectMapper objectMapper = new ObjectMapper();

    public JacksonRedisSerializer(int bigDataSize) {
        this.bigDataSize = bigDataSize;
    }

    public JacksonRedisSerializer() {
        this.bigDataSize = Integer.MAX_VALUE;
    }

    @Override
    public byte[] serialize(Object o) throws SerializationException {
        byte[] bytes = new byte[0];
        try {
            bytes = objectMapper.writeValueAsBytes(o);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        if (bytes.length==0) {
            log.error("redis 写入数据异常");
        }
        return bytes;
    }

    @Override
    public Object deserialize(byte[] bytes) throws SerializationException {
        try {
            return objectMapper.readValue(bytes,Object.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
